package com.zxb.core.dds;

import java.lang.reflect.Method;

import cn.hutool.core.util.StrUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import lombok.AllArgsConstructor;
import lombok.Data;

/**
 * @author Zxb
 */
@Aspect
@Component
@Data
@AllArgsConstructor
public class DataSourceAspect implements Ordered {

    private DataSourceUtil ddsUtil;

    @Pointcut("@annotation(com.zxb.core.dds.DataSource)")
    public void pointCut() {
    }

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        DataSource ds = method.getAnnotation(DataSource.class);
        String value = ds.value();
        if (StrUtil.isNotBlank(value)) {
            ddsUtil.change(value);
        } else {
            ddsUtil.clear();
        }
        try {
            return point.proceed();
        } finally {
            ddsUtil.clear();
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
